<template>
  <div class="user-card">
    <h3 style="width: 100%;text-align: center;">个人信息</h3>
    <div class="row space" style="margin: 20px 0">
      <div class="avatar">
        <img :src="user.avatar" />
        <input
          class="file"
          type="file"
          accept="image/jpeg,image/jpg,image/png"
          @change="avatarChange"
        />
      </div>
      <div class="row space">
        <el-input v-if="isEditSelf" v-model="user.name" @input="noSpace" class="input"/>
        <el-text v-else size="large" style="margin: 0 5px">{{user.name}}</el-text>
        <el-tag :type="user.status == 0 ? 'success' : 'danger'">
          {{ user.status == 0 ? "正常" : "异常" }}
        </el-tag>
      </div>
    </div>
    <div class="row space">
      <el-tag class="title" type="warning">电话/登录账号</el-tag>
      <!-- <el-input v-if="isEditSelf" v-model="user.phone" class="input"/> -->
      <el-text size="large">{{ user.phone }}</el-text>
    </div>
    <div class="row space">
      <el-tag class="title" type="success">所属用户</el-tag>
      <el-text size="large">{{ user.clientName }}</el-text>
    </div>
    <div class="row space">
      <el-tag class="title">创建日期</el-tag>
      <el-text size="large">{{ user.dtCreate }}</el-text>
    </div>
    <div class="row center" v-if="!isEditSelf && !isEditPsw">
      <el-button type="danger" plain @click="isEditPsw = true">修改密码</el-button>
      <el-button type="success" @click="isEditSelf = true">修改信息</el-button>
    </div>
    <div class="col" v-if="isEditPsw">
      <el-tag type="danger" style="margin-top: 20px;margin-bottom: 10px;">密码不小于8位，包含大小写字母、数字、特殊字符，且至少出现一次</el-tag>
      <el-input v-model="psw.old" type="password" placeholder="请输入原密码" @input="noSpace" show-password class="input"/>
      <el-input v-model="psw.new1" type="password" placeholder="请输入新密码" @input="noSpace" show-password class="input"/>
      <el-input v-model="psw.new2" type="password" placeholder="请再次输入新密码" @input="noSpace" show-password class="input"/>
    </div>
    <div class="row center" v-if="isEditPsw">
      <el-button type="default" plain @click="setCancel">取消</el-button>
      <el-button type="danger" @click="setOperator('psw')" :loading="loading">确认</el-button>
    </div>
    <div class="row center" v-if="isEditSelf">
      <el-button type="default" plain @click="isEditSelf = false"
        >取消</el-button
      >
      <el-button type="success" @click="setOperator('name')" :loading="loading">确认</el-button>
    </div>
  </div>
</template>

<script>
import { getCurrentInstance, onMounted, reactive, ref } from "vue";
import util from "@/assets/js/util";
import http from "@/axios/http";
import { ElNotification } from "element-plus";
import mqtt from '@/assets/js/mqtt';
export default {
  setup(props, ctx) {
    const Global = getCurrentInstance().proxy;
    let user = reactive({
      code: Global.$var.user.code,
      id: Global.$var.user.id,
      username: Global.$var.user.username,
      name: Global.$var.user.name,
      phone: Global.$var.user.phone,
      avatar: Global.$var.user.avatar,
      power: Global.$var.user.power,
      clientName: Global.$var.user.clientName,
      status: Global.$var.user.status,
      dtCreate: Global.$var.user.dtCreate,
    });

    function mqttOnMsg() {
      mqtt.onMsg((t,m)=>{
        loading.value = false
        let r = JSON.parse(m)
        if (r.data.returnCode == 10000) {
          let d = r.data.data
          if (r.msgType == 53 || r.msgType == 58) {
          //console.log(d)
            let msg = ''
            if (isEditPsw.value) {
              msg = '密码修改成功'
            }
            if (isEditSelf.value) {
              Global.$var.user.name = d[0].name
              msg = '个人信息修改成功'
              ctx.emit("done", d);
            }
            if (!isNull(msg)) {
              ElNotification({
                type: "success",
                title: "设置成功",
                message: msg,
                duration: 1500,
              });
            }
            isEditPsw.value = false
            isEditSelf.value = false
          }
        }
      })
    }

    onMounted(()=>{
      mqttOnMsg()
    })

    let loading = ref(false)
    let isEditSelf = ref(false);
    let isEditPsw = ref(false);
    let psw = reactive({
      old: "",
      new1: "",
      new2: "",
    });

    function setOperator(f) {
      let d = {};
      d.id = user.id;
      d.flag = f;
      d.msg = "";
      if (f == "avatar") {
        d.avatar = user.avatar;
      } else if (f == "name") {
        if (isNull(user.name)) {
          d.msg = "姓名不能为空";
        } else if (util.isAdmin(user.name)) {
          d.msg = '姓名不能包含“超级管理员”或“默认操作员”字样'
        } else d.name = user.name;
      } else if (f == "psw") {
        if (psw.new1 != psw.new2) {
          d.msg = "两次输入的新密码不一致";
        } else {
          d.password = psw.new1;
        }
      } else {
        return;
      }
      if (!isNull(d.msg)) {
        ElNotification({
          type: "warning",
          title: "个人信息修改失败",
          message: d.msg,
        });
        return;
      }
      loading.value = true
      let msgCode = 53
      if (f == "psw") msgCode = 58
      let topic = mqtt.TOPIC_REQ+msgCode
      let p = {}
      p.msgType = msgCode
      p.clientId = user.id
      p.userName = user.username
      let m = {}
      if (f == 'name') {
        m.Id = user.code
        m.name = d.name
        p.message = {}
        p.message.operator = JSON.stringify(m)
      }
      if (f == 'psw') {
        m.id = user.code
        m.old_pwd = psw.old
        m.new_pwd = d.password
        p.message = m
      } 
    //console.log(f+'操作员自身',JSON.stringify(p))
      mqtt.publish(topic,JSON.stringify(p))
    }

    async function avatarChange(e) {
    //console.log(e);
      let m = "";
      let f = e.target.files[0];
      if (f.size > 100 * 1024) {
        m = "图片不能大于100k";
      } else {
        let r = await util.fileToBase64(f);
        if (r.indexOf("data:image/") >= 0) user.avatar = r;
        else m = "无效的图片格式";
      }
      if (isNull(m)) {
        setOperator("avatar");
      } else {
        ElNotification({
          type: "warning",
          title: "头像设置失败",
          message: m,
        });
      }
    }
    function setCancel() {
      isEditSelf.value = false
      isEditPsw.value = false
      user.name = Global.$var.user.name;
    }

    function isNull(v) {
      return util.isNull(v);
    }

    function noSpace() {
      user.name = user.name.replace(/\s/g, '');  
      psw.old = psw.old.replace(/\s/g, '');  
      psw.new1 = psw.new1.replace(/\s/g, '');  
      psw.new2 = psw.new2.replace(/\s/g, '');  
    }

    return {
      user,
      loading,
      isEditSelf,
      isEditPsw,
      psw,
      avatarChange,
      setOperator,
      setCancel,
      isNull,
      noSpace,
    };
  },
};
</script>

<style lang="scss" scoped >
.user-card {
  width: auto;
  height: auto;
  .row {
    display: flex;
    flex-direction: row;
    .title {
      margin: 5px;
      margin-right: 15px;
    }
    .input{
      width: 240px;
      margin: 5px;
    }
  }
  .col {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    .input{
      width: 240px;
      margin: 5px;
    }
  }
  .row.space {
    width: 100%;
    align-items: center;
    justify-content: space-between;
  }
  .row.center {
    width: 100%;
    align-items: center;
    justify-content: center;
    padding-top: 30px;
  }
}
.avatar {
  cursor: pointer;
  position: relative;
  img {
    width: 64px;
    height: auto;
  }
  .file {
    position: absolute;
    top: 0;
    left: 0;
    width: 64px;
    height: 64px;
    opacity: 0;
    cursor: pointer;
  }
}
.pop-over {
  display: flex;
  align-items: center;
  border: 1px solid red;
}
</style>